import { constantRouterMap, asyncRouterMap } from '@/router'
/**
 * 通过route.path和route.meta.title判断是否与当前用户权限匹配
 * @param menuOfRole 当前用户的权限菜单
 * @param route 需要根据权限动态加载的路由
 */
function hasPermission(menuOfRole, route) {
  // 如果在meta中设置了title，就根据path和title去匹配
  if (route.path && route.meta && route.meta.title) {
    const menu = { path: route.path, title: route.meta.title }
    // 这个方法必须保证对象的顺序为{path:'/dashboard',title:'首页'}
    if (JSON.stringify(menuOfRole).indexOf(JSON.stringify(menu)) > -1) {
      return true
    } else {
      return false
    }
  } else {
    // 如果没有设置，就表示没有权限
    return false
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRouterMap
 * @param menuOfRole 当前用户的权限菜单
 * [
 *   {path:'/dashboard',title:'首页'}，
 *   {path:'/information',title:'信息管理'}，
 *   {path:'/information/administrator',title:'系统人员管理'}，
 *   {path:'/information/user',title:'注册用户管理'}，
 *   {path:'/information/role',title:'角色权限管理'}，
 * ]
 */
export function filterAsyncRoutes(routes, menuOfRole, parentPath = '') {
  const res = []

  routes.forEach(route => {
    // 拷贝route对象
    const tmp = {
      ...route
    }
    tmp.path = parentPath + tmp.path
    if (hasPermission(menuOfRole, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, menuOfRole, tmp.path + '/')
      }
      res.push(tmp)
    }
  })
  return res
}
const permission = {
  state: {
    routers: [],
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers // 匹配到的router
      state.routers = constantRouterMap.concat(routers) // 最终生成的router
    }
  },
  actions: {
    GenerateRoutes({ commit }, userInfo) {
      return new Promise(resolve => {
        let accessedRoutes
        if (userInfo.roles.includes('admin')) {
          accessedRoutes = asyncRouterMap
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRouterMap, userInfo.menuList)
        }
        commit('SET_ROUTERS', accessedRoutes)
        resolve(accessedRoutes)
      })
    }
  }
}

export default permission
